#-*- coding:utf-8 -*-
import kivy
kivy.require('1.8.0')

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.clock import Clock
import game

class GameOver(FloatLayout):
    pass

class GameGrid(FloatLayout):
    game = game.game()
    table = game.draw()
    score = game.getscore
    touchpos = 0
    #print table
    def __init__(self,**kwargs):
        super(GameGrid,self).__init__(**kwargs)
        from kivy.base import EventLoop
        EventLoop.window.bind(on_keyboard=self.hook_keyboard)

        Clock.schedule_interval(self.redraw,1.0/30.0)
             
    def redraw(self,time):
        self.ids['highscore'].text = 'HighScore:'+str(self.score())
        self.ids['score'].text = 'Score:'+str(self.score())
        for i in xrange(4):
            for j in xrange(4):
                color = self.table[i][j]/2*0.05
                self.ids['Btn%s%s'%(i,j)].text = str(self.table[i][j]) if self.table[i][j]!=0 else ''
                self.ids['Btn%s%s'%(i,j)].background_color = [1,1-color,1-color,1]
        if self.game.isover():        
            #self.clear_widgets()
            self.add_widget(GameOver())
            #gameover = 'GAMEOVER'
            #n = 0
            #for i in xrange(4):
             #   for j in xrange(4):
              #      self.ids['Btn%s%s'%(i,j)].background_color = [1,1,1,1]
               #     try:self.ids['Btn%s%s'%(i,j)].text = gameover[n]
                #    except:self.ids['Btn%s%s'%(i,j)].text = ''
                 #   n+=1
        
    def hook_keyboard(self,window,keycode,*args):
        print str(keycode)
        key = {
                   119:self.game.up,
                   115:self.game.down,
                   97:self.game.left,
                   100:self.game.right
                  }
        try:key[keycode]()
        except:print keycode
        return True
    
    def on_touch_down(self,touch):
        print(touch.pos)
        self.touchpos = touch.pos
    
    def on_touch_move(self,touch):
        pass#print(touch.pos)
    
    def on_touch_up(self,touch):
        print(touch.pos)
        if touch.pos[0] - self.touchpos[0] >= 100:self.game.right()
        elif touch.pos[0] - self.touchpos[0] <= -100:self.game.left()
        elif touch.pos[1] - self.touchpos[1] >= 100:self.game.up()
        elif touch.pos[1] - self.touchpos[1] <= -100:self.game.down()
        else:pass
        
    def on_pause(self):
        return True
    
class GameApp(App): 
    pass
    
if __name__ == '__main__':
    GameApp().run()